package mysql1

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

//配置结构体
type MysqlConfig struct {
	Host      string
	Port      int
	User      string
	PassWorld string
	Name      string
}


// 获取dsn
func GetSqlPath() string{
	// 配置对象
	var SqlConfig = MysqlConfig{
		Host:      "127.0.0.1",
		Port:      3306,
		User:      "root",
		PassWorld: "wsy",
		Name:      "gotest",
	}
	// 路径拼接, 路径字符串;
	var SqlPath = strings.Join( []string{
		SqlConfig.User,
		":",
		SqlConfig.PassWorld,
		"@tcp(",
		SqlConfig.Host,
		":",
		strconv.FormatInt(int64(SqlConfig.Port), 10),

		")/",
		SqlConfig.Name,
		"?charset=utf8&parseTime=true",
		}, "")

	return SqlPath

}



type Video struct {
	gorm.Model
	Title       string
	Description string
	URL         string
}
// 打印video一些字段
func (v Video) PrintSelf() {
	fmt.Println("<", v.Title, v.Description, v.URL, ">")
}

// 全局数据库入口
var DB *gorm.DB


func GetDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open(GetSqlPath()), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	db.AutoMigrate(&Video{})
	return db
}


func GetDBCloseFunc() (*gorm.DB, func()) {
	db := GetDB()
	dba, _ := db.DB()
	return db, func() {
		dba.Close()
	}
}

//// 创建数据
//func CreateVideo(db *gorm.DB, video Video) error {
//	result := db.Create(video)
//	return result.Error
//}
//
//// 查询数据
//func GetVideoByID(db *gorm.DB, id uint) (*Video, error) {
//	var video Video
//	result := db.First(&video, id)
//	return &video, result.Error
//}
//
//// 更新数据
//func UpdateVideo(db *gorm.DB, video *Video) error {
//	result := db.Save(video)
//	return result.Error
//}
//
//// 删除数据
//func DeleteVideo(db *gorm.DB, video *Video) error {
//	result := db.Delete(video)
//	return result.Error
//}
//
//func TestVideo() {
//	//添加数据
//	fmt.Println("add Video object")
//	CreateVideo(DB, Video{
//		Model:       gorm.Model{},
//		Title:       "大电影",
//		Description: "好看",
//		URL:         "http://www.haokan.com",
//	})
//	fmt.Println("add Video object")
//}
